/*
Jump Game
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

*/
#include <iostream>
#include <vector>
#include <map>

using namespace std;

class Solution1 {
public:
	vector<int> spiralOrder(vector<vector<int> > &matrix) {
		vector<int> result;

		if (matrix.empty())
			return result;

		int beginX = 0, endX = matrix[0].size() - 1;
		int beginY = 0, endY = matrix.size() - 1;
		while (true)
		{
			//From left to right
			for (int i = beginX; i <= endX; ++i)
				result.push_back(matrix[beginY][i]);
			if (++beginY > endY)break;

			//from top down
			for (int i = beginY; i <= endY; ++i)
				result.push_back(matrix[i][endX]);
			if (beginX > --endX)break;


			//from right to left
			for (int i = endX; i >= beginX; --i)
				result.push_back(matrix[endY][i]);
			if (beginY > --endY)break;

			//from down to top
			for (int i = endY; i >= beginY; --i)
				result.push_back(matrix[i][beginX]);
			if (++beginX > endX)break;
		}

		return result;

	}
};

class Solution {
public:
	vector<vector<int> > generateMatrix(int n) {
		vector<vector<int> > result;

		if (n == 0)
		{
			return result;
		}
		vector<int> temp(n,0);
		for (int i = 0; i < n ; i++)
		{
			result.push_back(temp);

		}
		int beginX = 0, endX = n - 1;
		int beginY = 0, endY = n - 1;
		int item = 1;

		while (true)
		{
			//From left to right
			for (int i = beginX; i <= endX; ++i)
			{
				result[beginY][i] = item;
				item++;
			}
				
			if (++beginY > endY)break;

			//from top down
			for (int i = beginY; i <= endY; ++i)
			{
				result[i][endX] = item;
				item++;
				
			}
			if (beginX > --endX)break;


			//from right to left
			for (int i = endX; i >= beginX; --i)
			{
				result[endY][i] = item;
				item++;
			}
			if (beginY > --endY)break;

			//from down to top
			for (int i = endY; i >= beginY; --i)
			{
				result[i][beginX] = item;
				item++;
			}
			if (++beginX > endX)break;
		}

		return result;
	}
};

int main(int argc, char * argv[])
{

	vector<vector<int> > result;
	int a;


	for (int i = 1; i < argc; i++)
	{
		cout << argv[i] << " ";
		a = atoi(argv[i]);
		//nums.push_back(a);
	}

	cout << endl;
	//cout << "The size of nums: " << nums.size() << endl;

	Solution s;
	result = s.generateMatrix(a);
	
	cout <<"Result" << endl;


	for (int i = 0; i < result.size() - 1; i++)
	{
		for (int j = 0; j < result[i].size()-1; j++)
		{
			cout << result[i][j] << " ";
		}

		cout << endl;
	}
	cout << endl;
	system("pause");
	return 0;
}